Skip to content

chore: update-usage-limit-subscription#3

Merged
agreea merged 2 commits into
mainfrom
fix-usage-example
Dec 10, 2025
Merged

chore: update-usage-limit-subscription#3
agreea merged 2 commits into
mainfrom
fix-usage-example

Conversation

@joeysabs

@joeysabs joeysabs commented Dec 10, 2025

Copy link
Copy Markdown
Collaborator

Making changes to the usage-limit-subscription example project that reflect recent changes to the sdk

Summary by CodeRabbit

Release Notes

  • Documentation

    • Simplified getting started guide by removing complex manual package linking prerequisites.
  • Dependencies

    • Updated @flowglad/nextjs from 0.12.3 to 0.15.0.
    • Added new flowglad library (0.0.1) for core functionality.
  • Improvements

    • Enhanced authentication mechanisms for API routes to ensure secure customer session handling.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Dec 10, 2025

Copy link
Copy Markdown

Walkthrough

Authentication is moved to session-based per-request handling: static Flowglad instances were replaced by a factory that accepts a customerExternalId, API routes now extract user IDs from auth sessions, and the README was simplified while dependencies were updated.

Changes

Cohort / File(s) Summary
Documentation
usage-limit-subscription/README.md
Removed yalc-related prerequisite and link/unlink steps; simplified Getting Started and script references; renumbered setup steps.
Dependencies & Scripts
usage-limit-subscription/package.json
Bumped @flowglad/nextjs from 0.12.3 to 0.15.0; added new flowglad dependency ^0.0.1; simplified dev/start script references (removed yalc commands).
Flowglad client factory
usage-limit-subscription/src/lib/flowglad.ts
Removed static flowgladServer export; added export const flowglad(customerExternalId: string) factory that configures FlowgladServer with a getCustomerDetails hook reading session (returns { email, name }); error message changed to "User not authenticated".
API route handlers
usage-limit-subscription/src/app/api/flowglad/[...path]/route.ts, usage-limit-subscription/src/app/api/usage-events/route.ts
Replaced previous server-wide Flowglad wiring with per-request client creation via flowglad(...); added getCustomerExternalId using auth.api.getSession(headers()) to extract user.id (401 if absent); switched to nextRouteHandler export pattern in flowglad route and removed prior flowgladServer usage.

Sequence Diagram

sequenceDiagram
    participant Client
    participant API as Next.js API Route
    participant Auth as auth.api
    participant Session as Session Store
    participant Flowglad as FlowgladServer (per-request)

    Client->>API: HTTP request (GET/POST)
    API->>Auth: auth.api.getSession(headers)
    Auth->>Session: lookup session
    Session-->>Auth: session (user)
    Auth-->>API: session with user

    alt user.id present
        API->>API: extract user.id as customerExternalId
        API->>Flowglad: flowglad(customerExternalId) // create client
        Flowglad->>Auth: getCustomerDetails(headers)
        Auth->>Session: lookup session
        Session-->>Auth: user details (email, name)
        Auth-->>Flowglad: return {email, name}
        API->>Flowglad: perform billing/usage operations
        Flowglad-->>API: operation result
        API-->>Client: 200 + result
    else no user
        API-->>Client: 401 Unauthorized
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • Check getCustomerExternalId and getCustomerDetails session extraction and error messages
  • Verify nextRouteHandler integration and exported GET/POST destructuring
  • Ensure per-request flowglad(...) instantiation does not leak context and is properly scoped
  • Confirm dependency bump compatibility and updated scripts in package.json

Poem

🐇 I hop through sessions, soft and spry,
I fetch your name and email on the fly,
No static ghosts, each request a bloom,
Flowglad wakes per-user in the room,
Goodbye yalc, hello tidy sky! 🎉

Pre-merge checks and finishing touches

❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Title check ❓ Inconclusive The title is vague and generic. It uses non-descriptive language ('update') that doesn't convey what was actually changed in the usage-limit-subscription example. Provide a more specific title that describes the main changes, such as 'refactor: migrate usage-limit-subscription to new Flowglad SDK API' or 'chore: update usage-limit-subscription for SDK v0.15.0'
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix-usage-example

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between efe8a7c and 4375254.

📒 Files selected for processing (1)
  • usage-limit-subscription/package.json (2 hunks)
🔇 Additional comments (3)
usage-limit-subscription/package.json (3)

21-22: Clarify yalc script removal intent.

The AI summary states "removal of yalc-related steps," yet the link:packages and unlink:packages scripts (lines 21-22) remain in the file. Either these should be removed as part of this SDK migration chore, or their continued presence should be intentional. Please clarify.


25-25: Pre-release dependency version warrants caution.

The new flowglad dependency is pinned to version ^0.0.1, a pre-release. While acceptable for example projects, be aware that 0.0.1 versions often include breaking changes between patches. Ensure that the integration code in other files can handle potential future updates, or consider pinning to an exact version if stability is critical.

Additionally, verify that the version bump of @flowglad/nextjs from 0.12.3 to 0.15.0 does not introduce breaking changes in the route handlers and client code.

Also applies to: 38-38


12-12: Dev server port mismatch with past review feedback.

Line 12 shows "dev": "next dev" without an explicit port. Next.js defaults to port 3000, but a past review comment flagged that the README references port 3001 and needs updating. Verify whether:

  1. The dev script should be updated to "next dev -p 3001" to match the intended port, or
  2. The documentation should reference port 3000 (the default).

Ensure consistency across package.json scripts and documentation.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
usage-limit-subscription/README.md (1)

83-89: Update the localhost URL to match the configured port.

The dev server is configured to run on port 3001 in package.json, but this documentation still references port 3000.

 ### 5. Start Development Server

 ```bash
 bun dev

-Open http://localhost:3000 to see the application.
+Open http://localhost:3001 to see the application.


</blockquote></details>
<details>
<summary>usage-limit-subscription/src/app/api/usage-events/route.ts (1)</summary><blockquote>

`103-122`: **`usageMeterId` is extracted and validated but not passed to `createUsageEvent()`.**

The code extracts `usageMeterId` at line 104 and validates its presence (lines 106-113), but it's never passed to `createUsageEvent()` at line 117. Other examples in the codebase (generation-based-subscription and tiered-usage-gated-subscription) pass `usageMeterId` to this API call, indicating the parameter should be included here as well. Either add `usageMeterId` to the `createUsageEvent()` call, or remove the extraction and validation if it's no longer required by the API.

</blockquote></details>

</blockquote></details>
🧹 Nitpick comments (2)
usage-limit-subscription/src/app/api/flowglad/[...path]/route.ts (1)

6-18: Unused req parameter and potential request context issue.

The req parameter in getCustomerExternalId is unused - instead, headers() from next/headers is called directly. This works in Node.js runtime but consider whether passing headers from req would be more explicit and avoid potential issues with request context in edge scenarios.

Also verify that the flowglad factory function integrates correctly with nextRouteHandler. The factory expects a customerExternalId string, so ensure nextRouteHandler calls it with the value returned by getCustomerExternalId.

 export const { GET, POST } = nextRouteHandler({
   flowglad,
-  getCustomerExternalId: async (req) => {
+  getCustomerExternalId: async () => {
     const session = await auth.api.getSession({
       headers: await headers(),
     });
usage-limit-subscription/src/lib/flowglad.ts (1)

8-20: Consider the redundant session fetching.

When this factory is used, the session is often fetched twice: once by the caller to obtain customerExternalId, and again inside getCustomerDetails. While this may be by design (the callback could be called lazily), consider whether the session could be passed in or cached to reduce redundant auth calls.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f30e840 and efe8a7c.

⛔ Files ignored due to path filters (1)
  • usage-limit-subscription/bun.lock is excluded by !**/*.lock
📒 Files selected for processing (5)
  • usage-limit-subscription/README.md (3 hunks)
  • usage-limit-subscription/package.json (3 hunks)
  • usage-limit-subscription/src/app/api/flowglad/[...path]/route.ts (1 hunks)
  • usage-limit-subscription/src/app/api/usage-events/route.ts (2 hunks)
  • usage-limit-subscription/src/lib/flowglad.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
usage-limit-subscription/src/app/api/usage-events/route.ts (1)
usage-limit-subscription/src/lib/flowglad.ts (1)
  • flowglad (5-23)
🔇 Additional comments (7)
usage-limit-subscription/README.md (1)

48-53: Documentation simplification looks good.

The removal of yalc-related prerequisites and the streamlined setup flow align well with the dependency updates in package.json.

usage-limit-subscription/src/app/api/usage-events/route.ts (2)

53-61: Authentication flow implemented correctly.

The session-based authentication properly retrieves the user ID and returns a 401 response for unauthenticated requests. This aligns well with the factory pattern in flowglad.ts.


48-51: Transaction ID generation is acceptable for idempotency.

The combination of timestamp and random string provides sufficient uniqueness for idempotency purposes. No security concern here as this is not used for authentication or authorization.

usage-limit-subscription/src/app/api/flowglad/[...path]/route.ts (1)

13-15: Thrown error may not produce a proper HTTP response.

Throwing a generic Error inside getCustomerExternalId may not result in a structured HTTP 401 response to the client. Verify that nextRouteHandler from @flowglad/nextjs/server catches this error and converts it to an appropriate HTTP response.

usage-limit-subscription/src/lib/flowglad.ts (2)

5-23: Factory pattern implementation looks correct.

The per-request factory pattern properly encapsulates the FlowgladServer configuration with session-based customer details.


17-20: Empty string fallbacks may cause downstream issues.

If email or name is undefined, empty strings are returned. Verify that the Flowglad API handles empty strings gracefully, especially for email which is typically required for customer identification.

usage-limit-subscription/package.json (1)

38-38: Verify production-readiness of the flowglad package.

The package only has version 0.0.1 published with no updates or newer releases. While the ^0.0.1 constraint is safe for pre-1.0 packages, the lack of development activity and single-version release history suggests this package may not be production-ready. Confirm this dependency aligns with your stability requirements.

Comment thread usage-limit-subscription/package.json Outdated
"preinstall": "bunx --bun only-allow bun",
"scripts": {
"dev": "next dev",
"dev": "next dev -p 3001",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Port change noted.

The dev server now runs on port 3001. Note that the README at line 89 still references http://localhost:3000 - this should be updated to port 3001 for consistency.

🤖 Prompt for AI Agents
In usage-limit-subscription/package.json around line 12 the dev script changed
the Next.js dev server to port 3001; update the README (line 89) to reference
http://localhost:3001 instead of http://localhost:3000 to keep documentation
consistent — open usage-limit-subscription/README.md, change the URL at line 89
(and any other occurrences of :3000) to :3001, save and run a quick search to
ensure no other docs or examples still point to port 3000.

@agreea agreea merged commit 4f20059 into main Dec 10, 2025
2 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Dec 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants